package cn.xiyun.xiyuncc.exception;

import cn.xiyun.xiyuncc.enums.OperationExceptionEnum;
import cn.xiyun.xiyuncc.result.JSONResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理
 */
//@ControllerAdvice
@RestControllerAdvice
public class EntireExceptionDispose {
    // 此注解做异常捕获
    @ExceptionHandler(value = Exception.class)
    public JSONResult systemException(Exception exception) {
        exception.printStackTrace();
        return JSONResult.error(OperationExceptionEnum.SYSTEM_EXCEPTION);
    }

    // 此注解做异常捕获
    @ExceptionHandler(value = OperationException.class)
    public JSONResult runningException(OperationException ex) {
        ex.printStackTrace();
        return JSONResult.error(ex.getMessage(), ex.getCode());

    }

    // 此注解做异常捕获
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public JSONResult runningException(MethodArgumentNotValidException ex) {
        ex.printStackTrace();
        StringBuffer err = new StringBuffer();
        //ex.bindingResult.errors
        ex.getBindingResult().getAllErrors().forEach(list ->
                err.append(list.getDefaultMessage() + "/")


        );
        String s = err.toString();
        //长度-1
        s = s.substring(0, s.length() - 1);
        return JSONResult.error(s, "parameter_error_1654651");

    }

}